import { _decorator, Component, UITransform, view } from "cc";
const { ccclass, property } = _decorator;

@ccclass("BgControl")
export class BgControl extends Component {
  speed = 200;

  // 边界值
  private _boundaryValue = 0;

  start() {
    const childUITransform = this.node.children[0].getComponent(UITransform);
    const childHeight = childUITransform.contentSize.height;
    const dH = view.getDesignResolutionSize().height;

    this._boundaryValue = dH / 2 + childHeight / 2 + (childHeight - dH) / 2;

    // 注意 cocos 的设置的位置，是相对于设计分辨率的
    // 比如设计分辨率是 480 * 852，那么要在右上角的话就需要设置 (480,852) [以右下角为原点坐标]
    this.node.children[1].setPosition(
      this.node.position.x,
      this._boundaryValue
    );
  }

  update(deltaTime: number) {
    if (
      this.node.position.y <
      -1 * this.node.children[0].getComponent(UITransform).height
    ) {
      this.node.setPosition(this.node.position.x, 0);
    } else {
      this.node.setPosition(
        this.node.position.x,
        this.node.position.y - this.speed * deltaTime
      );
    }

    // 不要用这种方式，这种方式会出现黑边
    // this.node.children.forEach((node) => {
    //   if (node.position.y <= this._boundaryValue * -1) {
    //     node.setPosition(node.position.x, this._boundaryValue);
    //   } else {
    //     node.setPosition(
    //       node.position.x,
    //       node.position.y - this.speed * deltaTime
    //     );
    //   }
    // });
  }
}
